package com.groupscore.user.controller;

import com.groupscore.user.pojo.User;
import com.groupscore.user.service.UserService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;
    /**
     * 查询全部列表
     */
    @GetMapping
    public Result findAll(){
        return new Result(true, StatusCode.OK, "查询成功",userService.findAll());
    }

    /**
     * 增加用户
     */
    @PostMapping
    public Result add(@RequestBody User user){
        userService.add(user);
        return new Result(true, StatusCode.OK, "增加用户成功");
    }

    /**
     * 用户登陆
     * @param u
     * @return
     */
    @RequestMapping(value="/login",method=RequestMethod.POST)
    @CrossOrigin
    public Result login(@RequestBody User u){
        User user = userService.findByNameAndPassword(u.getName(),u.getPassword());
        if(user!=null){
            String token = jwtUtil.createJWT(user.getId(),user.getName(),"user");
            Map map = new HashMap();
            map.put("token", token);
            map.put("name", user.getName());
            map.put("nikename", user.getNikename());
            map.put("id",user.getId());
            return new Result(true,StatusCode.OK,"登陆成功", map);
        }else{
            return new Result(false,StatusCode.LOGINERROR,"用户名或密码错误");
        }
    }

    @GetMapping("/info")
    @CrossOrigin
    public Result info(String token){
        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null) {
            return new Result(true,StatusCode.OK,"返回消息",userService.findUserById(claims.get("jti")+""));
        }
        return new Result(false, StatusCode.ACCESSERROR,"无权访问");
    }
    @GetMapping("/logout")
    @CrossOrigin
    public Result logout(){
        return new Result(true, StatusCode.OK, "退出成功");
    }
}
